<?php
/**
 * Created by PhpStorm .
 * User: 杜磊磊
 * Date: 2020/7/2
 * Time: 16:34
 */
namespace app\common\business;
use app\common\model\mysql\User as UserModel;
use app\common\lib\str;
use app\common\lib\Time;

class User
{
    public $userObj = null;

    public function __construct()
    {
        $this->userObj = new UserModel();
    }

    public function login($data)
    {
        $redisCode = cache(config("redis.code_pre").$data['phone_number']);
        if (empty($redisCode) || $redisCode != $data['code']){
            throw new \think\Exception("不存在该验证码",config("status.null_code"));
        }
        //需要去判断是否有用户记录 phone_number
        //生成token
        $user = $this->userObj->getUserByPhoneNumber($data['phone_number']);
        if (!$user){
            //
            $username = 'singwang-'.$data['phone_number'];
            $userData = [
                'username' => $username,
                'phone_number' => $data['phone_number'],
                'type' => $data['type'],
                'status' => config("status.table_normal"),
                'last_login_time' => time(),
            ];
            try {
                $this->userObj->save($userData);
                $this->userObj->id;
            }catch (\Exception $e){
                throw new \think\Exception('数据库内部异常');
            }
        }else{
            //更新
            $userData = [
                'last_login_time' => time(),
            ];
            $this->userObj->updateById($user['id'],$userData);

        }
        $token = Str::getLoginToken($data['phone_number']);
        $redisDate = [
            'id' => $user->id,
            'username' => $user->username,
        ];
        $res = cache(config("redis.token_pre").$token,$redisDate,Time::userLoginExpiresTime($data['type']));
        return $res ? ["token"=>$token,'username'=>$user->username] : false;
    }

    /**
     * 返回正常用户数据
     * @param $id
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNormalUserById($id)
    {
        $user = $this->userObj->getUserById($id);
        if (!$user || $user->staus != config("status.table_normal")){
            return false;
        }
        return $user->toArray();
    }

    /**
     * 返回正常用户数据
     * @param $username
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNormalUserByUsername($username)
    {
        $user = $this->userObj->getUserByUsername($username);
        if (!$user || $user->staus != config("status.table_normal")){
            return false;
        }
        return $user->toArray();
    }

    public function update($id,$data)
    {
        $user = $this->getNormalUserById($id);
        if (!$user){
            throw new \think\Exception("不存在该用户");
        }
        $userResult = $this->getNormalUserByUsername($data["username"]);
        if($userResult &&  $userResult['id'] != $id)
        {
            throw new \think\Exception("该用户已经存在请重新设置");
        }
        return $this->userObj->updateById($id,$data);
    }


}